package com.zx.zxblog.controller;

import com.github.pagehelper.PageInfo;
import com.zx.zxblog.entity.enums.SysConfigEnum;
import com.zx.zxblog.entity.pojo.Message;
import com.zx.zxblog.entity.pojo.User;
import com.zx.zxblog.entity.vo.MessageVO;
import com.zx.zxblog.service.MessageService;
import com.zx.zxblog.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * className=MessageController
 * package=com.zx.zxblog.controller
 * description:
 *
 * @Author:SKEZhi
 * @Create:2024/4/17 - 11:19
 * @Version: v1.0
 */
@Controller
public class MessageController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private SysConfigService sysConfigService;



    //显示留言板页面
    @GetMapping(value = "/message")
    public String message(Model model, @RequestParam(defaultValue = "1") Integer pageNum) {

        PageInfo<MessageVO> pageInfo = messageService.getMessageList(pageNum);
        // 获取作者
        String author = sysConfigService.getByEnums(SysConfigEnum.AUTHOR).getValue();

        model.addAttribute("page",pageInfo);
        model.addAttribute("author",author);
        // 更新总浏览量

        return "message";
    }

    //查询评论列表
    @CrossOrigin
    @GetMapping(value = {"/messagecomment","/messagecomment/{pageNum}"})
    public String messageComment(@PathVariable(value = "pageNum",required = false) Integer pageNum, Model model) {
        if (pageNum == null){
            pageNum = 1;
        }
        PageInfo<MessageVO> pageInfo = messageService.getMessageList(pageNum);
        model.addAttribute("page",pageInfo);

        return "message :: messageList";
    }

    //新增留言
    @PostMapping("/message")
    public String message(Message message, HttpSession session, Integer pageNum)  {

        User user = (User) session.getAttribute("user");
        //如果是管理员，设置管理员的权限
        if (user != null) {
            message.setAvatar(user.getAvatar());
            message.setAdminMessage(true);
        }
        messageService.save(message);//将评论信息保存数据库

        return "redirect:/messagecomment/"+pageNum;


    }

    //删除评论
    @GetMapping("/message/delete/{id}")
    public String delete(@PathVariable("id") Long id,HttpSession session,Integer pageNum){
        User user = (User) session.getAttribute("user");
        //如果是管理员
        if(user != null){
            messageService.removeById(id);
        }
        return "redirect:/message?pageNum="+pageNum;

    }



}
